package com.orhon.smartcampus.modules.baseinfo.fetcher;


import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.modules.base.entity.Schools;
import com.orhon.smartcampus.modules.base.gqlModel.GQLSchool;
import com.orhon.smartcampus.modules.base.mm.SchoolMapper;
import com.orhon.smartcampus.modules.baseinfo.dao.SemesterDao;
import com.orhon.smartcampus.modules.baseinfo.dao.TimetableDao;
import com.orhon.smartcampus.modules.baseinfo.entity.Semester;
import com.orhon.smartcampus.modules.baseinfo.entity.Timetable;
import com.orhon.smartcampus.modules.baseinfo.entity.TimetableItem;
import com.orhon.smartcampus.modules.baseinfo.gqlModel.GQLSemester;
import com.orhon.smartcampus.modules.baseinfo.gqlModel.GQLTimetable;
import com.orhon.smartcampus.modules.baseinfo.gqlModel.GQLTimetableItem;
import com.orhon.smartcampus.modules.baseinfo.mm.SemesterMapper;
import com.orhon.smartcampus.modules.baseinfo.mm.TimetableItemMapper;
import com.orhon.smartcampus.modules.baseinfo.mm.TimetableMapper;

import com.orhon.smartcampus.modules.user.dao.TokenService;
import com.orhon.smartcampus.utils.R;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TimetableFetcher implements DataFetcher {


	@Autowired
	TimetableDao timetableDao;

	@Autowired
	TokenService tokenService;

	@Override
	public Object get(DataFetchingEnvironment env) throws Exception {
		String token = tokenService.getSystemToken();
		if(token==null) {
			return  R.NoLogin();
		}
		Long schoolId = JwtUtils.getSchoolId(token);

		int id = Integer.parseInt(env.getArgument("id").toString());

		String hql = "from Timetable where deleted_at = null and id = "+id+" and school_id = " + schoolId;
		Timetable item =  timetableDao.findId(hql, null);
		if(item!=null) {
			GQLSchool gqlSchool= null;
			if (env.getSelectionSet().contains("school")){
				Schools schools = item.getBaseSchoolsBySchoolId();
				gqlSchool = SchoolMapper.MAPPER.toSchool(schools);
			}
			
			List<GQLTimetableItem> gqlTimetableItem= null;
			if (env.getSelectionSet().contains("items")){
				List<TimetableItem> items = item.getItems();
				gqlTimetableItem = TimetableItemMapper.MAPPER.toTimetableItemList(items);
			}

			GQLTimetable gqlTimetable = TimetableMapper.MAPPER.toTimetable(item);
			gqlTimetable.setSchool(gqlSchool);
			gqlTimetable.setItems(gqlTimetableItem);
			return gqlTimetable;
		}
		return null;
	}


}
